<script setup>
	//  1. 网络请求
	//  2. Promise 应用 
	import { ref } from 'vue';
	import { onPullDownRefresh, onShow } from '@dcloudio/uni-app'

	// 获取-图书列表
	const bookList = ref([])
	const getBookList = async () => {
		// 开启 loading 动画效果
		uni.showLoading({ title: '数据加载中...' })
		// async await 异步 等待 网络请求
		const res = await uni.request({
			method:'GET',
			url: 'https://hmajax.itheima.net/api/books',
			data: { creator: '东华理工' }
		})
		console.log(res)
		// 保存后端返回的数据
		bookList.value = res.data.data
		// 关闭 loading 动画效果
		uni.hideLoading()
	}
	
	// 页面显示，重新获取最新列表数据
	onShow(() => {
	    getBookList()
	})
	
	// 下拉刷新
	onPullDownRefresh(async () => {
		// 重新获取图书列表
	   await getBookList()
	   // 停止下拉刷新
	   uni.stopPullDownRefresh()
	})
	
	const deleteBook = async (id) => {
	    await uni.request({
			method:'DELETE',
			// 路径参数，直接拼接到路径上
			url: `https://hmajax.itheima.net/api/books/${id}`,
			data: {}
		})
		uni.showToast({ title: '删除成功' })
		// 删除成功，重新获取最新图书列表
		getBookList()
	}
</script>

<template>
	<navigator url="/pages/book-add/book-add">
		<button class="add-book-button" type="primary">新增图书</button>
	</navigator>
	<view class="book-list">
		<view class="book-item row" v-for="item in bookList" :key="item.id">
			<image class="book-cover" src="../../static/ic_public_cover.png" mode=""></image>
			<view class="book-info column">
				<text class="book-name">书名：{{ item.bookname }}</text>
				<text class="book-author">作者：{{ item.author }}</text>
				<text class="book-publisher">出版社：{{ item.publisher }}</text>
				<view class="book-options row">
					<button class="book-options-button" type="primary" size="mini">查看</button>
					<button @click="deleteBook(item.id)" class="book-options-button" type="warn" size="mini">删除</button>
				</view>
			</view>
		</view>
	</view>
</template>

<style lang="scss">
	.add-book-button {
		background-color: $uni-color-primary;
		margin: 20rpx;
	}
	.book-list {
		.book-item {
			padding: 20rpx;

			&:not(:last-child) {
				border-bottom: 1rpx solid #ddd;
			}
		}

		.book-cover {
			width: 200rpx;
			height: 200rpx;
			margin-right: 20rpx;
		}

		.book-options {
			margin-top: auto;
		}

		.book-options-button {
			margin-left: 0;
			margin-right: 20rpx;
		}
	}
</style>